﻿using MesBSW.BLL.Mes;
using MesBSW.DAL.CustomDB;
using MesBSW.DAL.MesDB;
using MesBSW.DAL.MesDTO;
using MesBSW.Tools;
using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesBSW.View.Search
{
    public partial class SearchProdScanFrm : UIPage
    {
        public SearchProdScanFrm()
        {
            InitializeComponent();
        }

        #region "内部变量"
        private ProdProcScanControler _ctrl = new ProdProcScanControler();
        private List<SiteInfo> _site_list = new List<SiteInfo>();
        private List<SiteInfo> _parent_list = new List<SiteInfo>();
        private List<StatusInfo> _status_list = new List<StatusInfo>();

        private List<TargetProdProcessDTO> _target_list = new List<TargetProdProcessDTO>();
        #endregion

        #region "控件事件"
        /// <summary>
        /// 界面Loadging时，读入相应资料信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchProdScanFrm_Load(object sender, EventArgs e)
        {
            this._status_list = this._ctrl.SearchAllStatus();
            this._site_list = this._ctrl.FindAllSiteInfo();
            if (this._site_list != null && this._site_list.Count > 0)
            {
                var query = this._site_list.Where(q => q.ParentID == 0);
                this._parent_list = query != null && query.Count() > 0 ? query.ToList<SiteInfo>() : new List<SiteInfo>();
            }

            this.InitBusinessComombox();
            this.InitParentSiteComombox();

            this.uiPagination1.PageSize = 50;
            this.txtPageSize.Text = "50";

            LanguageTools.ChangeControlTextForLangType(this, MainFrm.CurrLanguage);
        }

        /// <summary>
        /// 点击查询按钮查询数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            int tmpInt = 0;
            int pageSize = int.TryParse(txtPageSize.Text.Trim(), out tmpInt) ? tmpInt : 0;
            if (pageSize <= 0)
            {
                UIMessageBox.ShowError("每页显示数量不能小于或等于0！");
            }
            else
            {
                this.SearchProdForCondition(1, pageSize);
                this.DataGridViewRowColoration();
            }
        }

        /// <summary>
        /// 根据条件对数据行染色
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void DataGridViewRowColoration()
        {
            foreach (DataGridViewRow dgvr in this.dgvProd.Rows)
            {
                if (dgvr.Cells["prod_status_dgv1"].Value.ToString() == "已完成")
                {
                    dgvr.DefaultCellStyle.BackColor = Color.Green;
                }
            }
        }

        /// <summary>
        /// 更改页面时查询数据 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pagingSource"></param>
        /// <param name="pageIndex"></param>
        /// <param name="count"></param>
        private void uiPagination1_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            int tmpInt = 0;
            int pageSize = int.TryParse(txtPageSize.Text.Trim(), out tmpInt) ? tmpInt : 0;
            if (pageSize <= 0)
            {
                UIMessageBox.ShowError("每页显示数量不能小于或等于0！");
            }
            else
            {
                this.SearchProdForCondition(pageIndex, pageSize);
            }
        }
        #endregion

        #region "内部方法"
        /// <summary>
        /// 根据登陆用户可以操作的部门设定事业部下拉列表的值
        /// </summary>
        private void InitBusinessComombox()
        {
            this.cmbBus.Items.Clear();

            DataTable tmpDt = new DataTable();
            tmpDt.Columns.Add("id", typeof(int));
            tmpDt.Columns.Add("name", typeof(string));

            int deptid = int.TryParse(MainFrm.LoginUser.base_dept_id.ToString(), out deptid) ? deptid : 0;

            using (MesDB ctx = new MesDB())
            {
                DataRow firRow = tmpDt.NewRow();
                firRow["id"] = 0;
                firRow["name"] = "全部";
                tmpDt.Rows.Add(firRow);

                var query = from a in ctx.BaseDeptModel
                            where a.id == deptid
                            select new { A = a };

                foreach (var item in query)
                {
                    DataRow addRow = tmpDt.NewRow();
                    addRow["id"] = item.A.id;
                    addRow["name"] = item.A.dept_name;
                    tmpDt.Rows.Add(addRow);
                }
            }

            //if (MainFrm.LoginUser.UseDetpList != null && MainFrm.LoginUser.UseDetpList.Count > 0)
            //{
            //    DataRow firRow = tmpDt.NewRow();
            //    firRow["id"] = 0;
            //    firRow["name"] = "全部";
            //    tmpDt.Rows.Add(firRow);

            //    foreach (var dept in MainFrm.LoginUser.UseDetpList)
            //    {
            //        DataRow addRow = tmpDt.NewRow();
            //        addRow["id"] = dept.id;
            //        addRow["name"] = dept.dept_name;
            //        tmpDt.Rows.Add(addRow);
            //    }
            //}

            this.cmbBus.DataSource = tmpDt;
            this.cmbBus.DisplayMember = "name";
            this.cmbBus.ValueMember = "id";
        }


        /// <summary>
        /// 根据登陆用户设定可以查看的大站
        /// </summary>
        private void InitParentSiteComombox()
        {
            this.cmbParentSite.Items.Clear();

            DataTable tmpDt = new DataTable();
            tmpDt.Columns.Add("id", typeof(int));
            tmpDt.Columns.Add("name", typeof(string));

            int deptid = int.TryParse(MainFrm.LoginUser.base_dept_id.ToString(), out deptid) ? deptid : 0;

            using (MesDB ctx = new MesDB())
            {
                DataRow firRow = tmpDt.NewRow();
                firRow["id"] = 0;
                firRow["name"] = "全部";
                tmpDt.Rows.Add(firRow);

                var query = from a in ctx.SiteInfos
                            where a.deptId == deptid && a.ParentID==0
                            orderby a.SiteCode
                            select new { A = a };

                foreach (var item in query)
                {
                    DataRow addRow = tmpDt.NewRow();
                    addRow["id"] = item.A.ID;
                    addRow["name"] = item.A.SiteName;
                    tmpDt.Rows.Add(addRow);
                }
            }

            //if (MainFrm.LoginUser.UseDetpList != null && MainFrm.LoginUser.UseDetpList.Count > 0 &&
            //        this._site_list != null && this._site_list.Count > 0)
            //{
            //    var ids = MainFrm.LoginUser.UseDetpList.Select(q => q.id).ToList();
            //    var query = this._site_list.Where(q => q.ParentID == 0 && ids.Contains(q.deptId)).OrderBy(q => q.ID);
            //    if (query != null && query.Count() > 0)
            //    {
            //        DataRow firRow = tmpDt.NewRow();
            //        firRow["id"] = 0;
            //        firRow["name"] = "全部";
            //        tmpDt.Rows.Add(firRow);

            //        foreach (var site in query)
            //        {
            //            DataRow addRow = tmpDt.NewRow();
            //            addRow["id"] = site.ID;
            //            addRow["name"] = site.SiteName;
            //            tmpDt.Rows.Add(addRow);
            //        }
            //    }
            //}

            this.cmbParentSite.DataSource = tmpDt;
            this.cmbParentSite.DisplayMember = "Name";
            this.cmbParentSite.ValueMember = "id";
        }

        /// <summary>
        /// 为每个工单产生一个大站点的进度条
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        private BreadcrumbModel InitBreadCrunbModel(TargetProdProcessDTO target)
        {
            BreadcrumbModel resBean = new BreadcrumbModel();

            resBean.Location = new Point(0, 0);
            resBean.SelectedColor = Color.LimeGreen;
            resBean.ItemWidth = 100;

            List<string> itemList = new List<string>();
            if (target.SiteGroup != null && target.SiteGroup.SiteInfoList != null)
            {
                foreach (var site in target.SiteGroup.SiteInfoList.OrderBy(s => s.Sort))
                {
                    if (this._parent_list != null && this._parent_list.Count > 0)
                    {
                        var parentQuery = this._parent_list.Where(p => p.ID == site.SiteInfo.ParentID);
                        if (parentQuery != null && parentQuery.Count() > 0 && parentQuery.First().SiteName != null && itemList.Contains(parentQuery.First().SiteName) == false)
                        {
                            itemList.Add(parentQuery.First().SiteName);
                        }
                    }
                }
            }

            resBean.ItemString.AddRange(itemList);

            int tmpIndex = -1;

            var currsiteid = this._site_list.Where(a => a.ID == target.CurrSiteID).Select(b => b.ParentID);

            if (currsiteid.Count() > 0)
            {
                var currsitename = this._parent_list.Where(a => a.ID == currsiteid.First()).Select(b => b.SiteName);
                tmpIndex = resBean.ItemString.IndexOf(currsitename.First());
            }

            foreach (var parSite in resBean.ItemString)
            {
                List<SiteInfo> childList = new List<SiteInfo>();
                if (this._parent_list != null && this._parent_list.Count > 0)
                {
                    var parentQuery = this._parent_list.Where(p => p.SiteName == parSite);
                    if (parentQuery != null && parentQuery.Count() > 0)
                    {
                        var childQuery = target.SiteGroup.SiteInfoList.Where(s => s.SiteInfo.ParentID == parentQuery.First().ID).OrderByDescending(q => q.Sort);
                        if (childQuery != null && childQuery.Count() > 0)
                        {
                            //Boolean isComp = true;
                            SiteInfo maxSite = childQuery.First().SiteInfo;

                            if (target.scanList != null && target.scanList.Count > 0)
                            {
                                var tmpQuery = target.scanList.Where(q => q.SiteInfoID == maxSite.ID);
                                decimal scanQty = tmpQuery.Sum(q => q.ScanQty);
                                //if (scanQty >= target.ProdQty)
                                //{
                                //    isComp = true;
                                //}
                                //else
                                //{
                                //    isComp = false;
                                //}
                            }
                            //else
                            //{
                            //    isComp = false;
                            //}

                            //if (isComp == true)
                            //{
                            //tmpIndex = resBean.ItemString.IndexOf(parSite);
                            //}
                            //else
                            //{
                            //    break;
                            //}
                        }
                    }
                }
            }
            resBean.ItemIndex = tmpIndex;
            return resBean;
        }

        /// <summary>
        /// 将工单信息由实体类转变成DataTable
        /// </summary>
        /// <param name="targetList"></param>
        /// <returns></returns>
        private DataTable ChangeTargetProdListToDataTable(List<TargetProdProcessDTO> targetList)
        {
            DataTable resDt = new DataTable();
            resDt.Columns.Add("index", typeof(int));
            resDt.Columns.Add("id", typeof(int));
            resDt.Columns.Add("process", typeof(BreadcrumbModel));
            resDt.Columns.Add("prod_number", typeof(string));
            resDt.Columns.Add("mto_number", typeof(string));
            resDt.Columns.Add("mo_number", typeof(string));
            resDt.Columns.Add("goods_number", typeof(string));
            resDt.Columns.Add("goods_spe", typeof(string));
            resDt.Columns.Add("goods_length", typeof(decimal));
            resDt.Columns.Add("in_stock_status", typeof(string));
            resDt.Columns.Add("in_stock_qty", typeof(decimal));
            resDt.Columns.Add("curr_site_id", typeof(int));
            resDt.Columns.Add("curr_site", typeof(string));
            resDt.Columns.Add("prod_status_id", typeof(int));
            resDt.Columns.Add("prod_status", typeof(string));
            resDt.Columns.Add("urgent_status_id", typeof(int));
            resDt.Columns.Add("urgent_status", typeof(string));
            resDt.Columns.Add("err_status_id", typeof(int));
            resDt.Columns.Add("err_status", typeof(string));
            resDt.Columns.Add("plan_date", typeof(string));
            resDt.Columns.Add("prod_qty", typeof(decimal));
            resDt.Columns.Add("clear_qty", typeof(decimal));
            resDt.Columns.Add("surp_qty", typeof(decimal));


            if (targetList != null && targetList.Count > 0)
            {
                foreach (var target in targetList.OrderBy(q => q.ProdSort))
                {
                    DataRow addRow = resDt.NewRow();
                    addRow["index"] = target.ProdSort;
                    addRow["id"] = target.ID;
                    addRow["process"] = target.BreadcrumbModel;
                    addRow["prod_number"] = target.ProdNumber;
                    addRow["mo_number"] = target.MoNumber;
                    addRow["mto_number"] = target.MtoNumber;
                    addRow["goods_number"] = target.GoodsNumber;
                    addRow["goods_spe"] = target.GoodsSpe;
                    addRow["goods_length"] = Math.Round(target.GoodsLength ?? 0, 3);
                    addRow["in_stock_status"] = "未接收";
                    addRow["in_stock_qty"] = 0;
                    if (target.InStockDetails != null && target.InStockDetails.Count > 0)
                    {
                        addRow["in_stock_status"] = "已接收";
                        addRow["in_stock_qty"] = target.InStockDetails.Sum(q => q.erp_qty);
                    }
                    addRow["curr_site_id"] = target.CurrSiteID;
                    addRow["curr_site"] = "";
                    if (this._site_list != null && this._site_list.Count > 0)
                    {
                        var query = this._site_list.Where(s => s.ID == target.CurrSiteID);
                        if (query != null && query.Count() > 0)
                        {
                            addRow["curr_site"] = query.First().SiteName;
                        }
                    }
                    addRow["prod_status_id"] = target.ProdStatusID;
                    addRow["urgent_status_id"] = target.UrgentStatusID;
                    addRow["err_status_id"] = target.ErrStatusID;
                    addRow["prod_status"] = target.ProdStatus != null ? target.ProdStatus.StatusValue : "";
                    addRow["urgent_status"] = target.UrgentStatus != null ? target.UrgentStatus.StatusValue : "";
                    addRow["err_status"] = target.ErrStatus != null ? target.ErrStatus.StatusValue : "";

                    //由于贝斯旺尚未有生产周期，先将交货日期屏蔽
                    //if (target.SourceCycle != null && target.SourceCycle.PlanDate.HasValue)
                    //{
                    //    addRow["plan_date"] = target.SourceCycle.MaxDate.Value.ToString("yyyy-MM-dd");
                    //}
                    addRow["plan_date"] = "";
                    addRow["prod_qty"] = Math.Round(target.ProdQty ?? 0, 2);

                    decimal clearQty = 0;
                    if (target.scanList != null && target.scanList.Count > 0)
                    {
                        var query = target.scanList.Where(s => s.SiteInfoID == 20);
                        if (query != null && query.Count() > 0)
                        {
                            clearQty = query.Sum(q => q.ScanQty);
                        }
                    }

                    addRow["clear_qty"] = Math.Round(clearQty, 2);
                    addRow["surp_qty"] = Math.Round((target.ProdQty ?? 0) - clearQty, 2);

                    resDt.Rows.Add(addRow);
                }
            }

            return resDt;
        }

        /// <summary>
        /// 设置加急工单的背景颜色 
        /// </summary>
        private void SetDataRowBgcolor()
        {
            if (this.dgvProd.Rows.Count > 0)
            {
                foreach (DataGridViewRow row in this.dgvProd.Rows)
                {
                    if (row.Cells["urgent_status_dgv1"].Value != null && row.Cells["urgent_status_dgv1"].Value.ToString().Equals("红单加急"))
                    {
                        row.DefaultCellStyle.BackColor = Color.Red;
                    }
                    else if (row.Cells["urgent_status_dgv1"].Value != null && row.Cells["urgent_status_dgv1"].Value.ToString().Equals("黄单加急"))
                    {
                        row.DefaultCellStyle.BackColor = Color.Yellow;
                    }
                }
            }
        }
        #endregion

        /// <summary>
        /// 根据条件查询工单
        /// </summary>
        /// <param name="pageIndex"></param>
        private void SearchProdForCondition(int pageIndex, int pageSize)
        {
            string tmpProdNumber = this.txtProdNumber.Text.Trim();
            string tmpMtoNumber = this.txtMtoNumber.Text.Trim();
            string tmpClientCode = this.txtClientCode.Text.Trim();
            string tmpSaler = this.txtSaler.Text.Trim();
            string tmpParentSite = this.cmbParentSite.Text.Trim().Equals("全部") ? "" : this.cmbParentSite.Text.Trim();
            string tmpDept = this.cmbBus.SelectedValue != null && this.cmbBus.SelectedValue.ToString().Equals("0") == false ? this.cmbBus.SelectedValue.ToString() : "";
            int tmpStatus = this.cmbProdStatus.Text.Equals("撤销") ? 1 :
                                this.cmbProdStatus.Text.Equals("未上线") ? 2 :
                                this.cmbProdStatus.Text.Equals("生产中") ? 3 :
                                this.cmbProdStatus.Text.Equals("已完成") ? 4 : 0;
            string compBeginDay = this.dtpBeginDay.Checked ? this.dtpBeginDay.Value.ToString("yyyy-MM-dd") : "";
            string compEndDay = this.dtpEndDay.Checked ? this.dtpEndDay.Value.ToString("yyyy-MM-dd") : "";

            int totalPage = 0;

            if (pageSize <= 0)
            {
                UIMessageBox.ShowError("每页显示数量不能小于或等于0！");
            }
            else
            {
                List<TargetProdProcessDTO> tmpList = this._ctrl.SearchProdScanForProcedure(tmpProdNumber, tmpMtoNumber, tmpParentSite, tmpDept.ToString(),
                                                                                                tmpClientCode, tmpSaler, tmpStatus, compBeginDay, compEndDay,
                                                                                                pageIndex, pageSize, ref totalPage);
                if (tmpList != null && tmpList.Count > 0)
                {
                    //由于贝斯旺尚没有成品入库功能，暂时屏蔽查询入库数量
                    SqlSugarClient Db = SqlSugares.GetInstance();
                    var prodNumberList = tmpList.Select(q => q.ProdNumber).ToList<string>();
                    List<In_stock_detail> inStockList = Db.Queryable<In_stock_detail>().Where(q => prodNumberList.Contains(q.prod_number)).ToList();
                    if (inStockList != null && inStockList.Count > 0)
                    {
                        foreach (var item in tmpList)
                        {
                            var inStockQuery = inStockList.Where(q => q.prod_number.Equals(item.ProdNumber));
                            if (inStockQuery != null && inStockList.Count() > 0)
                            {
                                item.InStockDetails = new List<In_stock_detail>();
                                item.InStockDetails.AddRange(inStockQuery);
                            }
                        }
                    }

                    foreach (TargetProdProcessDTO item in tmpList)
                    {
                        BreadcrumbModel tmpBean = this.InitBreadCrunbModel(item);
                        item.BreadcrumbModel = tmpBean;
                        var query1 = this._status_list.Where(q => q.ID == item.ProdStatusID);
                        item.ProdStatus = query1 != null && query1.Count() > 0 ? query1.First<StatusInfo>() : null;
                        var query2 = this._status_list.Where(q => q.ID == item.UrgentStatusID);
                        item.UrgentStatus = query2 != null && query2.Count() > 0 ? query2.First<StatusInfo>() : null;
                        var query3 = this._status_list.Where(q => q.ID == item.ErrStatusID);
                        item.ErrStatus = query3 != null && query3.Count() > 0 ? query3.First<StatusInfo>() : null;
                    }

                    DataTable tmpDt = this.ChangeTargetProdListToDataTable(tmpList);
                    this.dgvProd.DataSource = tmpDt;

                    if (this.dgvProd.Rows.Count > 0)
                    {
                        this.SetDataRowBgcolor();
                    }

                    this.uiPagination1.TotalCount = totalPage;
                    this.uiPagination1.PageSize = pageSize;
                }
                else
                {
                    UIMessageBox.ShowWarning("没有找到符合条件的工单信息！");
                }
            }
        }

        private void dgvProd_Sorted(object sender, EventArgs e)
        {
            if (this.dgvProd.Rows.Count > 0)
            {
                this.SetDataRowBgcolor();
            }
        }
    }
}
